<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useForm, useFormRules } from '@/hooks/common/form';
import { $t } from '@/locales';
import { fetchTenantSave } from '@/service/api';
import { useLoading } from '~/packages/hooks';

type Model = Api.System.Tenant.TenantFormModel;

defineOptions({ name: 'TenantFormDrawer' });

interface Props {
  operateType: UI.TableOperateType;
  rowData?: Api.System.Tenant.TenantRecord | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const { formRef, validate, restoreValidation } = useForm();
const { createRequiredRule, patternRules } = useFormRules();

function createDefaultModel(): Model {
  return {
    id: '',
    tenantCode: '',
    companyName: '',
    companyCode: '',
    contactName: '',
    contactPhone: '',
    contactEmail: '',
    address: '',
    domain: '',
    intro: '',
    remark: '',
    expiredTime: '',
    accountCount: -1,
    packageCode: '',
    enabled: 1
  };
}

const model = ref<Model>(createDefaultModel());

type RuleKey = Extract<
  Model,
  'tenantCode' | 'companyName' | 'companyCode' | 'contactPhone' | 'contactEmail' | 'domain' | 'enabled'
>;
const rules = ref<Record<RuleKey, App.Global.FormRule>>({
  tenantCode: createRequiredRule($t('form.required')),
  companyName: createRequiredRule($t('form.required')),
  companyCode: createRequiredRule($t('form.required')),
  contactPhone: patternRules.phone,
  contactEmail: patternRules.email,
  domain: patternRules.domain,
  enabled: createRequiredRule($t('form.enabled'))
});

const visible = defineModel<boolean>('visible', {
  default: false
});
const title = computed(() => {
  const titles: Record<UI.TableOperateType, string> = {
    add: '新增租户',
    edit: '编辑租户'
  };
  return titles[props.operateType];
});

function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model.value, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

const { loading, startLoading, endLoading } = useLoading(false);

async function handleSubmit() {
  try {
    await validate();
    startLoading();
    // request
    const { error } = await fetchTenantSave(model.value);
    // success
    if (error) return;
    window.$message?.success($t('common.updateSuccess'));
    closeDrawer();
    emit('submitted');
  } finally {
    endLoading();
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});
</script>

<template>
  <ElDrawer v-model="visible" :title="title" :close-on-click-modal="false" direction="rtl" size="450">
    <ElForm ref="formRef" :model="model" :rules="rules" label-position="top">
      <ElFormItem label="租户编码" prop="tenantCode">
        <ElInput v-model="model.tenantCode" placeholder="租户编码" maxlength="100" show-word-limit />
      </ElFormItem>
      <ElFormItem label="公司名称" prop="companyName">
        <ElInput v-model="model.companyName" placeholder="公司名称" maxlength="100" show-word-limit />
      </ElFormItem>
      <ElFormItem label="统一社会信用代码" prop="companyCode">
        <ElInput v-model="model.companyCode" placeholder="统一社会信用代码" maxlength="100" show-word-limit />
      </ElFormItem>
      <ElFormItem label="联系人" prop="contactName">
        <ElInput v-model="model.contactName" placeholder="联系人" maxlength="50" show-word-limit />
      </ElFormItem>
      <ElFormItem label="联系方式" prop="contactPhone">
        <ElInput v-model="model.contactPhone" placeholder="联系方式" maxlength="50" show-word-limit />
      </ElFormItem>
      <ElFormItem label="联系邮箱" prop="contactEmail">
        <ElInput v-model="model.contactEmail" placeholder="邮箱" maxlength="100" show-word-limit />
      </ElFormItem>
      <ElFormItem label="联系地址" prop="address">
        <ElInput v-model="model.address" placeholder="联系地址" maxlength="200" show-word-limit />
      </ElFormItem>
      <ElFormItem label="企业域名" prop="domain">
        <ElInput v-model="model.domain" placeholder="企业域名" maxlength="100" show-word-limit />
      </ElFormItem>
      <ElFormItem label="公司简介" prop="intro">
        <ElInput v-model="model.intro" type="textarea" placeholder="公司简介" maxlength="500" show-word-limit />
      </ElFormItem>
      <ElFormItem label="备注" prop="remark">
        <ElInput v-model="model.remark" type="textarea" placeholder="备注" maxlength="500" show-word-limit />
      </ElFormItem>
      <ElFormItem label="过期时间" prop="expiredTime">
        <ElDatePicker
          v-model="model.expiredTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="过期时间"
          clearable
        />
      </ElFormItem>
      <ElFormItem :label="$t('form.enabled')" prop="enabled">
        <ElRadioGroup v-model="model.enabled">
          <ElRadio :label="$t('form.enabledOptions.enabled')" :value="1" />
          <ElRadio :label="$t('form.enabledOptions.disabled')" :value="0" />
        </ElRadioGroup>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElSpace v-loading="loading" :size="16">
        <ElButton @click="closeDrawer">{{ $t('common.cancel') }}</ElButton>
        <ElButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</ElButton>
      </ElSpace>
    </template>
  </ElDrawer>
</template>

<style scoped>
:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

:deep(.el-input) {
  width: 100% !important;
}
</style>
